package org.jeecg.util;

import com.baomidou.mybatisplus.core.toolkit.Assert;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import java.awt.print.PrinterJob;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *@Description: Java连接打印机 工具类(暂未使用,原因：获取到的打印机是服务器上的)
 *@Author: "zk"
 *@Date: 2024-09-18 17:49
 */
public class PrintUtil {

    /**
     * 获取打印机
     * 从当前主机连接的单个或多个打印机中,获取与传参名称相同的打印机,如果获取不到报错
     * @param printerName
     * @return
     */
    public static PrintService getPrinter(String  printerName) {
        PrintService[] printServices = PrinterJob.lookupPrintServices();
        Assert.notEmpty(printServices, "打印机连接异常,请联系管理员");
        // 获取已连接的打印机
        List<PrintService> printerList = Arrays.asList(printServices);
        Assert.notEmpty(printerList, "打印机连接异常,请联系管理员");
        // 使用ZD888T打印机
        List<PrintService> printServiceList = printerList.stream().filter(data -> data.getName().equals(printerName)).collect(Collectors.toList());
        Assert.notEmpty(printServiceList, "未查询到当前系统与" + printerName + "的连接信息,请联系管理员");
        return printServiceList.get(0);
    }

    /**
     * 设置打印参数
     * @param printNum 打印多少份
     * @param labelWide 打印机标签宽度
     * @param labelHeight 打印机标签高度
     * @return
     */
    public static PrintRequestAttributeSet getPrintParam(int printNum, int labelWide, int labelHeight) {
        // 设置打印参数
        PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
        // 打印1份
        printRequestAttributeSet.add(new Copies(printNum));
        // 设置长100mm,宽39mm(必须设置对应的尺寸,否则后续DocPrintJob.print()时打印机没有反应)
        printRequestAttributeSet.add(new MediaPrintableArea(0, 0, labelWide, labelHeight, MediaPrintableArea.MM));
        return printRequestAttributeSet;
    }

}
